const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context })

  let body = event
  if (event.body != undefined) {
    body = JSON.parse(event.body)
  }

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      console.log('身份验证失败')
      return { code: 403, message: '身份验证失败' }
    }

    console.log('身份验证成功，uid:', uid)

    // 2. 查询用户数据
    const db = uniCloud.database()
    const userRes = await db.collection('uni-id-users')
      .doc(uid)
      .field({ remainingCancelCount: true })
      .get()

    console.log('查询到的用户数据:', userRes.data)

    // 3. 处理字段不存在的情况
    if (!userRes.data.length || !userRes.data[0].hasOwnProperty('remainingCancelCount')) {
      console.log('remainingCancelCount 字段不存在，初始化为 3')
      await db.collection('uni-id-users').doc(uid).update({
        remainingCancelCount: 3 // 默认值为 3
      })
      return { code: 0, remainingCancelCount: 3 }
    }

    // 4. 已有字段直接返回
    const remaining = userRes.data[0].remainingCancelCount
    console.log(`获取到的 remainingCancelCount: ${remaining}`)

    return { 
      code: 0, 
      remainingCancelCount: remaining 
    }
  } catch (e) {
    console.error('服务器错误:', e)
    return { code: -4, message: '获取失败', error: e }
  }
}
